//
//  MainViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/3/29.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class MainViewController:BaseViewController, UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,DCPicscrollDelegate {
    
    var scrollView: UIScrollView!
    var collectionView: UICollectionView!
    var pageControl: UIPageControl!
    
    var tableView: UITableView!
    
    var rightArray = NSMutableArray()
    var unreadArray = NSMutableArray()
    
    var headerView : UIView!
    
    var heightScroll : CGFloat!
    
    let RightCollectionViewCellIdentifier = "RightCollectionViewCellIdentifier"
    
    var imageArray = NSArray()
    var idArray = NSMutableArray()
    var urlArray = NSMutableArray()
    
    //1212 - 使用代码构写、不需要使用这个初始化
//    required init?(coder aDecoder: NSCoder) {
//        super.init(coder: aDecoder)
//        
//        self.tabBarItem.image = UIImage.init(named: "32classb")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
//        self.tabBarItem.selectedImage = UIImage.init(named: "32classg")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
//        self.tabBarItem.title = "家校"
//        
//        self.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(hexString: "4e92df", alpha: 1)], for: UIControlState.selected)
//        
//    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "家校管家"

        self.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(hexString: "4e92df", alpha: 1)], for: UIControlState.selected)
        rightArray = getRightArray()
        
        InitViews()
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.refresh), name: NSNotification.Name(rawValue: "refreshRightNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.MainRightClick(_:)), name: NSNotification.Name(rawValue: "MainRightClick"), object: nil)
    }

    func InitViews() {
        
        headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH - 49 - 64))
        headerView.backgroundColor = UIColor.init(hexString: "f7f7f7", alpha: 1)
        
        var view: UIView!
        view = UIView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH/3 - 60))
        view.backgroundColor = UIColor.init(hexString: "f7f7f7", alpha: 1)
        view.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
        view.layer.shadowRadius = 2.0
        view.layer.shadowColor = UIColor.lightGray.cgColor
        view.layer.shadowOpacity = 0.8
        
        
        let imageArray = ["main1.png", "main2.png", "main3.png"]
        var picView: DCPicScrollView!
        picView = DCPicScrollView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH/3 - 60), withImageNames: imageArray)
        picView.titleData = nil
        picView.style = PageControlStyle.atCenter
        picView.backgroundColor = UIColor.clear
        picView.autoScrollDelay = 10.0
        view.addSubview(picView)
        
        
        let count = rightArray.count/13 + 1
        scrollView = UIScrollView.init(frame: CGRect(x: 0, y: view.frame.maxY+10, width: screenW, height: screenH*2/3 - 53 - 30))
        scrollView.backgroundColor = UIColor.clear
        scrollView.tag = 101
        scrollView.contentSize = CGSize(width: CGFloat(Float(count)) * screenW, height: 0)
        scrollView.isPagingEnabled = true;
        scrollView.showsVerticalScrollIndicator = false;
        scrollView.showsHorizontalScrollIndicator = false;
        scrollView.delegate = self
        
        heightScroll = scrollView.frame.height
        
        
        var fx: CGFloat = 0.0
        for i in 0...count - 1 {
            
            collectionView = UICollectionView.init(frame: CGRect(x: fx, y: 0, width: screenW , height: scrollView.frame.height), collectionViewLayout: RightCollectionFlowLayout.init())
            collectionView.tag = i
            collectionView.backgroundColor = UIColor.clear
            collectionView.register(RightCollectionViewCell.self, forCellWithReuseIdentifier: RightCollectionViewCellIdentifier)
            collectionView.scrollsToTop = true
            collectionView.delegate = self
            collectionView.dataSource = self
            scrollView.addSubview(collectionView)
            fx += screenW
        }
        print("scrollView X  = \(scrollView.contentOffset.x)")
        pageControl = UIPageControl.init(frame: CGRect(x: 0, y: scrollView.frame.maxY, width: screenW, height: 20))
        pageControl.backgroundColor = UIColor.white
        pageControl.tag = 201
        pageControl.numberOfPages = count
        pageControl.currentPageIndicatorTintColor = barColor
        pageControl.pageIndicatorTintColor = UIColor.init(hexString: "e2e2e2", alpha: 1)
        
        
        headerView.addSubview(pageControl)
        headerView.addSubview(view)
        headerView.addSubview(scrollView)
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH))
        tableView.backgroundColor = UIColor.white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
        tableView.tableHeaderView = headerView
        tableView.tableFooterView = UIView()
        tableView.showsVerticalScrollIndicator = false
        
        self.view.addSubview(tableView)
        
        tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(MainViewController.refresh))
    }
    
    /**
     轮播图的点击事件
     
     - parameter index: 0开始
     */
    func didSelectedImageView(at index: Int) {
        
        if urlArray.count != 0 {
            let str = urlArray.object(at: index) as! String
            if str.characters.count != 0 {
                let url = "\(urlArray.object(at: index) as! String)?id=\(idArray.object(at: index))"
                NotificationCenter.default.post(name: Notification.Name(rawValue: "imageViewSelectedNotification"), object: nil, userInfo: ["url" : url])
            }
        }else{
            
        }
        
    }
    /**
     刷新模块和未读
     */
    func refresh() {
        pageControl.updateCurrentPageDisplay()
//        let queue = DispatchQueue(label: "queue")
//        queue.async {
            let user = getUserPojo()
            let requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>37</t><sch>\(user.schid!)</sch><uid>\(user.userid!)</uid></channel></rss>"
            let url = server + adminwebapppi
        
            HttpPostUTF(url, requestXML: requestXML, finished: { (data, result, error) in
                
                if error == nil {
                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                    let rightArray = NSMutableArray()
                    if array.count != 0 {
                        rightArray.addObjects(from: array.arrayValue)
                    }
                    setRightArray(rightArray)
                    self.rightArray = getRightArray()
                    
                    let count = self.rightArray.count/13 + 1
                    for i in 0...count - 1 {
                        let collection: UICollectionView = self.scrollView.viewWithTag(i) as! UICollectionView
                        collection.reloadData()
                    }
                    self.tableView.reloadData()
                    self.tableView.header.endRefreshing()

                }else{
                    
                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                    self.tableView.header.endRefreshing()
                    
                }
            })
//        }
        
        
    }
    
    /**
     scrollview的滚动
     
     - parameter scrollView:
     */
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let current = (scrollView.contentOffset.x)/screenW
        pageControl.currentPage = Int(current)
        
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 12
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: RightCollectionViewCell = self.collectionView.dequeueReusableCell(withReuseIdentifier: RightCollectionViewCellIdentifier, for: indexPath) as! RightCollectionViewCell
        cell.backgroundColor = UIColor.white
        
        let tag = collectionView.tag
        let count = (indexPath as NSIndexPath).row + tag*12
        
        if count >= rightArray.count {
            cell.icon.image = UIImage.init(named: "")
            cell.title.text = ""
        }else {
            if rightArray.count != 0 {
                let dic = rightArray[count] as! NSDictionary
                let title = dic.object(forKey: "plugname") as! String
                let icon = dic.object(forKey: "plugimg") as! String
                
                cell.icon.image = UIImage.init(named: icon)
                cell.title.text = title
            }
        }
        
        return cell;
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let tag = collectionView.tag
        let count = (indexPath as NSIndexPath).row + tag*12
        
        if count >= rightArray.count {
            
        }else {
            let dic = rightArray[count] as! NSDictionary
            let modetype = dic.object(forKey: "modetype") as! String
            let apiUrl = dic.object(forKey: "apiurl") as! String
            
            NotificationCenter.default.post(name: Notification.Name(rawValue: "MainRightClick"), object: nil, userInfo: ["target" : modetype, "apiurl" : apiUrl])
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return unreadArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "MeTableViewCellIdentifier"
        
        let cell: MeTableViewCell = MeTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: identifier)
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        let dic: NSDictionary = unreadArray.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
        let icon = (dic.object(forKey: "plugimg") as! String).replacingOccurrences(of: " ", with: "")
        let unread = dic.object(forKey: "num") as! String
        let title = dic.object(forKey: "pname") as! String
        cell.icon.image = UIImage.init(named: icon)
        cell.title.text = "您有\(unread)条\(title)尚未查看"
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let dic: NSDictionary = unreadArray.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
        let icon = (dic.object(forKey: "plugimg") as! String).replacingOccurrences(of: " ", with: "")
        let title = dic.object(forKey: "pname") as! String
        let add = dic.object(forKey: "Add") as! String
        let plugid = dic.object(forKey: "plugid") as! String
        NotificationCenter.default.post(name: Notification.Name(rawValue: "OFFICENOTIFICATION"), object: nil, userInfo: ["target" : icon, "Add" : add, "plugid" : plugid, "title" : title])
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /**
     桐乡教育管家模块
     
     - parameter notification:
     */
    func MainRightClick(_ notification: Notification) {
        
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        let target = dic.object(forKey: "target") as! String
        let apiurl = dic.object(forKey: "apiurl") as! String
        
        switch target {
        case "1":
            /**
             *  班级活动
             */
            
            let classWork = ClassWorkViewController()
            classWork.apiurl = apiurl
            classWork.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(classWork, animated: true)
            break;
        case "2":
            /**
             *  班级荣誉
             */
            let honor = HonorViewController()
            honor.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(honor, animated: true)
            break;
        case "3":
            /**
             *  班级通知
             */
            let notice = NoticeViewController()
            notice.modetype = target
            notice.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(notice, animated: true)
            break;
        case "4":
            /**
             *  课程表
             */
            let course = CourseViewController()
            course.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(course, animated: true)
            break;
        case "5":
            /**
             *  桐乡教育统计
             */
            let bellStatisVC = BellStatisViewController()
            bellStatisVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(bellStatisVC, animated: true)
            break;
        case "6":
            /**
             *  家长关注
             */
            let parent = ParentFoucsViewController()
            parent.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(parent, animated: true)
            break;
        case "7":
            /**
             *  成长记录
             */
            let growth = GrowthViewController()
            growth.apiurl = apiurl
            growth.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(growth, animated: true)
            break;
        case "8":
            /**
             *  今日请假
             */
            let leave = LeaveViewController()
            leave.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(leave, animated: true)
            break;
        case "9":
            /**
             *  今日考勤
             */
            let attendance = AttendanceViewController()
            attendance.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(attendance, animated: true)
            break;
        case "10":
            /**
             *  桐乡教育日报
             */
            let dayReport = DayReportViewController()
            dayReport.apiurl = apiurl
            dayReport.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(dayReport, animated: true)
            break;
        case "11":
            /**
             *  作业备忘
             */
            let homeWork = HomeWorkViewController()
            homeWork.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(homeWork, animated: true)
            break;
        case "12":
            /**
             *  问卷调查
             */
            let suvery = SuveryViewController()
            suvery.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(suvery, animated: true)
            break;
        case "13":
            /// 班级圈
            let classCircle = ClassCircleViewController()
            classCircle.apiurl = apiurl
            classCircle.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(classCircle, animated: true)
            break
            
        case "14":
            // 全校通知
            let SchNotice = SchNoticeViewController()
            SchNotice.modetype = target
            SchNotice.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(SchNotice, animated: true)
            
            break
        default:
            TSMessage.showNotification(in: self, title: "提示", subtitle: "对不起，该模块权限尚未开放！请稍等", image: nil, type: TSMessageNotificationType.warning, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
            break;
        }
        
        
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
